import $store from "../store";

function init(url) {
  var ws = new WebSocket(url);
  //连接打开时触发
  ws.onopen = function() {
    $store.commit("initWsConn", ws);
  };
  //接收到消息时触发
  ws.onmessage = function(evt) {
    let data = JSON.parse(evt.data);
    if (data.code === -1) {
      $store.commit("seterrorData", data.msg);
      return;
    }
    switch (data.type) {
      case 0: {
        $store.commit("setPagesAndFlvData", data);
        break;
      }
      case 2: {
        $store.commit("updateProgress", data);
        break;
      }
      case 3: {
        $store.commit("setDwonLoadList", data.data);
        break;
      }
      case 4: {
        $store.commit("stopDownLoadVideo", data.data);
        break;
      }
      case 5: {
        $store.commit("restoreDownLoadVideo", data.data);
        break;
      }
    }
  };
  //连接关闭时触发
  ws.onclose = function() {
    $store.commit("initWsConn", null);
    //console.log("Connection closed." + evt);
  };
}

export default {
  init
};
